package com.example.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.util.Date;

@RestController
public class controller {

    @PostMapping("/c")
    public String handlePostRequest(@RequestBody Map<String, Object> requestData) {
        manifest.lianjie();
        String method = manifest.chuli(requestData);
        String res = c.zhixing(method);
        manifest.chongzhi();
        return res;
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        JSONObject j = new JSONObject();
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String fileType = "";

            if (StringUtils.hasText(fileName)) {
                if (fileName == null)
                    fileName = "S.jpg"; // 只是为了消除提醒
                int dotIndex = fileName.lastIndexOf(".");
                if (dotIndex >= 0 && dotIndex < fileName.length() - 1) {
                    fileType = fileName.substring(dotIndex + 1);
                }
            }

            String name =  (new Date().getTime()) + ""+gongju.suiji(11,99)+"." + fileType;
            System.out.println(name);

            // 指定保存文件的路径
            String filePath =  System.getProperty("user.dir") + File.separator + "files" + File.separator  + name;
            System.out.println(filePath);
            // 保存文件
            file.transferTo(new File(filePath));

            j.put("code", 200);
            j.put("data", name);
            // 返回文件名给前端
            String res = j.toString();
            j.clear();
            return res;

        } catch (IOException e) {
            j.put("code", 300);
            e.printStackTrace();
            String res = j.toString();
            j.clear();
            return res;
        }
    }

    @PostMapping("/p")
    public String handlePostRequest2(@RequestBody Map<String, Object> requestData) {
        manifest.lianjie();
        String method = manifest.chuli(requestData);
        String res = p.zhixing(method);
        manifest.chongzhi();
        return res;
    }

}
